"""
视频混剪系统主界面

参考剪映、Premiere Pro等专业视频编辑软件的布局设计
采用经典的四区域布局：素材库、预览窗口、属性面板、时间轴
"""

import tkinter as tk
from tkinter import ttk, messagebox
from pathlib import Path
import sys

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.video_editing_design_system import (
    VideoEditingDesignSystem, 
    create_video_button, create_toolbar_button, create_play_control_button,
    create_panel_frame, create_timeline_frame, create_preview_frame, create_toolbar_frame
)


class VideoEditingMainApp:
    """视频混剪系统主应用"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.setup_window()
        self.setup_styles()
        self.create_layout()
        
    def setup_window(self):
        """设置窗口"""
        self.root.title("🎬 视频混剪系统 - Video Mixing Studio")
        self.root.geometry("1400x900")
        self.root.minsize(1200, 800)
        
        # 设置窗口图标和背景
        self.root.configure(bg=VideoEditingDesignSystem.COLORS['bg_primary'])
        
        # 居中显示
        self.center_window()
    
    def center_window(self):
        """窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')
    
    def setup_styles(self):
        """设置样式"""
        self.style = VideoEditingDesignSystem.configure_styles()
    
    def create_layout(self):
        """创建布局 - 专业视频编辑软件布局"""
        # 主容器
        main_container = ttk.Frame(self.root)
        main_container.pack(fill="both", expand=True)
        
        # 顶部工具栏
        self.create_top_toolbar(main_container)
        
        # 主工作区域 - 分为上下两部分
        work_area = ttk.Frame(main_container)
        work_area.pack(fill="both", expand=True, padx=2, pady=2)
        
        # 上半部分：素材库 + 预览窗口 + 属性面板
        self.create_upper_area(work_area)
        
        # 下半部分：时间轴区域
        self.create_timeline_area(work_area)
        
        # 底部状态栏
        self.create_status_bar(main_container)
    
    def create_top_toolbar(self, parent):
        """创建顶部工具栏"""
        toolbar = create_toolbar_frame(parent)
        toolbar.pack(fill="x", pady=(0, 2))
        
        # 左侧：文件操作
        left_tools = ttk.Frame(toolbar, style='Toolbar.TFrame')
        left_tools.pack(side="left")
        
        file_buttons = [
            ("📁 新建项目", self.new_project),
            ("📂 打开项目", self.open_project),
            ("💾 保存项目", self.save_project),
            ("📤 导出视频", self.export_video)
        ]
        
        for text, command in file_buttons:
            btn = create_toolbar_button(left_tools, text, command)
            btn.pack(side="left", padx=(0, VideoEditingDesignSystem.SPACING['button_spacing']))
        
        # 中间：编辑工具
        center_tools = ttk.Frame(toolbar, style='Toolbar.TFrame')
        center_tools.pack(side="left", padx=(20, 0))
        
        edit_buttons = [
            ("✂️ 剪切", self.cut_clip),
            ("📋 复制", self.copy_clip),
            ("📌 粘贴", self.paste_clip),
            ("↶ 撤销", self.undo),
            ("↷ 重做", self.redo)
        ]
        
        for text, command in edit_buttons:
            btn = create_toolbar_button(center_tools, text, command)
            btn.pack(side="left", padx=(0, VideoEditingDesignSystem.SPACING['button_spacing']))
        
        # 右侧：视图控制
        right_tools = ttk.Frame(toolbar, style='Toolbar.TFrame')
        right_tools.pack(side="right")
        
        view_buttons = [
            ("🔍 缩放适应", self.zoom_fit),
            ("⚙️ 设置", self.show_settings)
        ]
        
        for text, command in view_buttons:
            btn = create_toolbar_button(right_tools, text, command)
            btn.pack(side="right", padx=(VideoEditingDesignSystem.SPACING['button_spacing'], 0))
    
    def create_upper_area(self, parent):
        """创建上半部分区域"""
        upper_frame = ttk.Frame(parent)
        upper_frame.pack(fill="both", expand=True, pady=(0, 2))
        
        # 左侧：素材库面板 (25%)
        self.create_media_library(upper_frame)
        
        # 中间：预览窗口 (50%)
        self.create_preview_area(upper_frame)
        
        # 右侧：属性面板 (25%)
        self.create_properties_panel(upper_frame)
    
    def create_media_library(self, parent):
        """创建素材库面板"""
        # 素材库容器
        media_container = ttk.Frame(parent)
        media_container.pack(side="left", fill="both", expand=False, padx=(0, 2))
        media_container.configure(width=300)  # 固定宽度
        media_container.pack_propagate(False)
        
        # 素材库面板
        media_panel = create_panel_frame(media_container, "📁 素材库")
        media_panel.pack(fill="both", expand=True)
        
        # 素材库工具栏
        media_toolbar = ttk.Frame(media_panel, style='Toolbar.TFrame')
        media_toolbar.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['md']))
        
        import_btn = create_video_button(media_toolbar, "📥 导入素材", self.import_media, 'Primary')
        import_btn.pack(side="left", padx=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        refresh_btn = create_video_button(media_toolbar, "🔄", self.refresh_media, 'Secondary')
        refresh_btn.pack(side="left")
        
        # 素材分类标签页
        media_notebook = ttk.Notebook(media_panel)
        media_notebook.pack(fill="both", expand=True)
        
        # 视频素材标签页
        video_frame = ttk.Frame(media_notebook)
        media_notebook.add(video_frame, text="🎬 视频")
        self.create_media_list(video_frame, "video")
        
        # 音频素材标签页
        audio_frame = ttk.Frame(media_notebook)
        media_notebook.add(audio_frame, text="🎵 音频")
        self.create_media_list(audio_frame, "audio")
        
        # 图片素材标签页
        image_frame = ttk.Frame(media_notebook)
        media_notebook.add(image_frame, text="🖼️ 图片")
        self.create_media_list(image_frame, "image")
        
        # 文字素材标签页
        text_frame = ttk.Frame(media_notebook)
        media_notebook.add(text_frame, text="📝 文字")
        self.create_media_list(text_frame, "text")
    
    def create_media_list(self, parent, media_type):
        """创建素材列表"""
        # 搜索框
        search_frame = ttk.Frame(parent)
        search_frame.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        search_entry = ttk.Entry(search_frame, font=VideoEditingDesignSystem.FONTS['body'])
        search_entry.pack(fill="x")
        search_entry.insert(0, f"搜索{media_type}素材...")
        
        # 素材列表
        list_frame = ttk.Frame(parent)
        list_frame.pack(fill="both", expand=True)
        
        # 创建滚动列表
        media_listbox = tk.Listbox(
            list_frame,
            bg=VideoEditingDesignSystem.COLORS['bg_secondary'],
            fg=VideoEditingDesignSystem.COLORS['text_primary'],
            selectbackground=VideoEditingDesignSystem.COLORS['primary'],
            selectforeground=VideoEditingDesignSystem.COLORS['text_primary'],
            borderwidth=0,
            highlightthickness=0,
            font=VideoEditingDesignSystem.FONTS['body']
        )
        
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=media_listbox.yview)
        media_listbox.configure(yscrollcommand=scrollbar.set)
        
        media_listbox.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 添加示例素材
        sample_items = {
            "video": ["📹 产品展示.mp4", "📹 模特试穿.mp4", "📹 使用场景.mp4"],
            "audio": ["🎵 背景音乐.mp3", "🎵 音效.wav", "🎵 配音.mp3"],
            "image": ["🖼️ 产品图片.jpg", "🖼️ 背景图.png", "🖼️ Logo.png"],
            "text": ["📝 标题模板", "📝 字幕模板", "📝 片尾字幕"]
        }
        
        for item in sample_items.get(media_type, []):
            media_listbox.insert(tk.END, item)
    
    def create_preview_area(self, parent):
        """创建预览区域"""
        # 预览容器
        preview_container = ttk.Frame(parent)
        preview_container.pack(side="left", fill="both", expand=True, padx=2)
        
        # 预览面板
        preview_panel = create_panel_frame(preview_container, "🎥 预览窗口")
        preview_panel.pack(fill="both", expand=True)
        
        # 预览控制工具栏
        preview_toolbar = ttk.Frame(preview_panel, style='Toolbar.TFrame')
        preview_toolbar.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['md']))
        
        # 播放控制按钮
        control_frame = ttk.Frame(preview_toolbar, style='Toolbar.TFrame')
        control_frame.pack()
        
        play_buttons = [
            ("⏮️", self.goto_start),
            ("⏪", self.step_backward),
            ("▶️", self.play_pause),
            ("⏩", self.step_forward),
            ("⏭️", self.goto_end)
        ]
        
        for text, command in play_buttons:
            btn = create_play_control_button(control_frame, text, command)
            btn.pack(side="left", padx=VideoEditingDesignSystem.SPACING['sm'])
        
        # 预览画面区域
        preview_frame = create_preview_frame(preview_panel)
        preview_frame.pack(fill="both", expand=True)
        
        # 预览画面占位
        preview_canvas = tk.Canvas(
            preview_frame,
            bg=VideoEditingDesignSystem.COLORS['bg_preview'],
            highlightthickness=0
        )
        preview_canvas.pack(fill="both", expand=True, padx=10, pady=10)
        
        # 添加预览占位文字
        preview_canvas.create_text(
            200, 100, 
            text="🎬 预览窗口\n\n将素材拖拽到时间轴开始编辑",
            fill=VideoEditingDesignSystem.COLORS['text_muted'],
            font=VideoEditingDesignSystem.FONTS['title_panel'],
            justify="center"
        )
        
        # 时间码显示
        timecode_frame = ttk.Frame(preview_panel, style='Timeline.TFrame')
        timecode_frame.pack(fill="x", pady=(VideoEditingDesignSystem.SPACING['sm'], 0))
        
        timecode_label = ttk.Label(
            timecode_frame, 
            text="00:00:00:00", 
            style='Timecode.TLabel'
        )
        timecode_label.pack()
    
    def create_properties_panel(self, parent):
        """创建属性面板"""
        # 属性容器
        props_container = ttk.Frame(parent)
        props_container.pack(side="right", fill="both", expand=False, padx=(2, 0))
        props_container.configure(width=300)  # 固定宽度
        props_container.pack_propagate(False)
        
        # 属性面板
        props_panel = create_panel_frame(props_container, "🎛️ 属性面板")
        props_panel.pack(fill="both", expand=True)
        
        # 属性标签页
        props_notebook = ttk.Notebook(props_panel)
        props_notebook.pack(fill="both", expand=True)
        
        # 视频属性
        video_props = ttk.Frame(props_notebook)
        props_notebook.add(video_props, text="🎬 视频")
        self.create_video_properties(video_props)
        
        # 音频属性
        audio_props = ttk.Frame(props_notebook)
        props_notebook.add(audio_props, text="🎵 音频")
        self.create_audio_properties(audio_props)
        
        # 特效属性
        effect_props = ttk.Frame(props_notebook)
        props_notebook.add(effect_props, text="✨ 特效")
        self.create_effect_properties(effect_props)
    
    def create_video_properties(self, parent):
        """创建视频属性控制"""
        # 基础属性
        basic_frame = ttk.LabelFrame(parent, text="基础属性", padding=VideoEditingDesignSystem.SPACING['md'])
        basic_frame.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['md']))
        
        # 位置控制
        ttk.Label(basic_frame, text="位置 X:", style='Muted.TLabel').pack(anchor="w")
        x_scale = ttk.Scale(basic_frame, from_=-100, to=100, orient="horizontal")
        x_scale.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        ttk.Label(basic_frame, text="位置 Y:", style='Muted.TLabel').pack(anchor="w")
        y_scale = ttk.Scale(basic_frame, from_=-100, to=100, orient="horizontal")
        y_scale.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        # 缩放控制
        ttk.Label(basic_frame, text="缩放:", style='Muted.TLabel').pack(anchor="w")
        scale_scale = ttk.Scale(basic_frame, from_=0.1, to=3.0, orient="horizontal")
        scale_scale.set(1.0)
        scale_scale.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        # 旋转控制
        ttk.Label(basic_frame, text="旋转:", style='Muted.TLabel').pack(anchor="w")
        rotation_scale = ttk.Scale(basic_frame, from_=0, to=360, orient="horizontal")
        rotation_scale.pack(fill="x")
    
    def create_audio_properties(self, parent):
        """创建音频属性控制"""
        # 音频控制
        audio_frame = ttk.LabelFrame(parent, text="音频控制", padding=VideoEditingDesignSystem.SPACING['md'])
        audio_frame.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['md']))
        
        # 音量控制
        ttk.Label(audio_frame, text="音量:", style='Muted.TLabel').pack(anchor="w")
        volume_scale = ttk.Scale(audio_frame, from_=0, to=200, orient="horizontal")
        volume_scale.set(100)
        volume_scale.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        # 静音按钮
        mute_var = tk.BooleanVar()
        mute_check = ttk.Checkbutton(audio_frame, text="🔇 静音", variable=mute_var)
        mute_check.pack(anchor="w")
    
    def create_effect_properties(self, parent):
        """创建特效属性控制"""
        # 特效列表
        effect_frame = ttk.LabelFrame(parent, text="特效库", padding=VideoEditingDesignSystem.SPACING['md'])
        effect_frame.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['md']))
        
        effects = ["✨ 淡入淡出", "🌟 闪光", "🎨 滤镜", "📐 裁剪", "🔄 转场"]
        for effect in effects:
            effect_btn = create_video_button(effect_frame, effect, style='Secondary')
            effect_btn.pack(fill="x", pady=VideoEditingDesignSystem.SPACING['xs'])
    
    def create_timeline_area(self, parent):
        """创建时间轴区域"""
        # 时间轴容器
        timeline_container = ttk.Frame(parent)
        timeline_container.pack(fill="x", pady=2)
        timeline_container.configure(height=250)  # 固定高度
        timeline_container.pack_propagate(False)
        
        # 时间轴面板
        timeline_panel = create_panel_frame(timeline_container, "🎞️ 时间轴")
        timeline_panel.pack(fill="both", expand=True)
        
        # 时间轴工具栏
        timeline_toolbar = ttk.Frame(timeline_panel, style='Toolbar.TFrame')
        timeline_toolbar.pack(fill="x", pady=(0, VideoEditingDesignSystem.SPACING['sm']))
        
        # 轨道控制
        track_buttons = [
            ("➕ 视频轨", self.add_video_track),
            ("➕ 音频轨", self.add_audio_track),
            ("🔍 缩放", self.zoom_timeline),
            ("📏 标尺", self.toggle_ruler)
        ]
        
        for text, command in track_buttons:
            btn = create_toolbar_button(timeline_toolbar, text, command)
            btn.pack(side="left", padx=(0, VideoEditingDesignSystem.SPACING['button_spacing']))
        
        # 时间轴主体
        timeline_main = create_timeline_frame(timeline_panel)
        timeline_main.pack(fill="both", expand=True)
        
        # 创建时间轴画布
        self.timeline_canvas = tk.Canvas(
            timeline_main,
            bg=VideoEditingDesignSystem.COLORS['bg_timeline'],
            highlightthickness=0
        )
        
        # 时间轴滚动条
        h_scrollbar = ttk.Scrollbar(timeline_main, orient="horizontal", command=self.timeline_canvas.xview)
        v_scrollbar = ttk.Scrollbar(timeline_main, orient="vertical", command=self.timeline_canvas.yview)
        
        self.timeline_canvas.configure(xscrollcommand=h_scrollbar.set, yscrollcommand=v_scrollbar.set)
        
        # 布局时间轴
        self.timeline_canvas.grid(row=0, column=0, sticky="nsew")
        h_scrollbar.grid(row=1, column=0, sticky="ew")
        v_scrollbar.grid(row=0, column=1, sticky="ns")
        
        timeline_main.grid_rowconfigure(0, weight=1)
        timeline_main.grid_columnconfigure(0, weight=1)
        
        # 绘制时间轴内容
        self.draw_timeline()
    
    def draw_timeline(self):
        """绘制时间轴内容"""
        canvas = self.timeline_canvas
        
        # 绘制时间标尺
        ruler_height = 30
        canvas.create_rectangle(0, 0, 1000, ruler_height, 
                               fill=VideoEditingDesignSystem.COLORS['bg_tertiary'], 
                               outline="")
        
        # 绘制时间刻度
        for i in range(0, 1000, 50):
            canvas.create_line(i, 0, i, ruler_height, 
                              fill=VideoEditingDesignSystem.COLORS['timeline_ruler'])
            if i % 100 == 0:
                time_text = f"{i//100}s"
                canvas.create_text(i+5, 15, text=time_text, 
                                  fill=VideoEditingDesignSystem.COLORS['text_primary'],
                                  anchor="w", font=VideoEditingDesignSystem.FONTS['timeline'])
        
        # 绘制轨道
        track_height = VideoEditingDesignSystem.SIZES['track_height']
        y_offset = ruler_height
        
        tracks = [
            ("🎬 视频轨道 1", VideoEditingDesignSystem.COLORS['video_track']),
            ("🎵 音频轨道 1", VideoEditingDesignSystem.COLORS['audio_track']),
            ("📝 字幕轨道", VideoEditingDesignSystem.COLORS['text_track'])
        ]
        
        for i, (track_name, track_color) in enumerate(tracks):
            y = y_offset + i * (track_height + 2)
            
            # 轨道背景
            canvas.create_rectangle(0, y, 1000, y + track_height,
                                   fill=VideoEditingDesignSystem.COLORS['bg_secondary'],
                                   outline=VideoEditingDesignSystem.COLORS['border_primary'])
            
            # 轨道标题
            canvas.create_text(10, y + track_height//2, text=track_name,
                              fill=VideoEditingDesignSystem.COLORS['text_primary'],
                              anchor="w", font=VideoEditingDesignSystem.FONTS['body'])
        
        # 绘制播放头
        canvas.create_line(100, 0, 100, 200, 
                          fill=VideoEditingDesignSystem.COLORS['timeline_cursor'], 
                          width=2)
    
    def create_status_bar(self, parent):
        """创建状态栏"""
        status_bar = ttk.Frame(parent, style='Toolbar.TFrame')
        status_bar.pack(fill="x", pady=(2, 0))
        
        # 左侧状态信息
        status_left = ttk.Frame(status_bar, style='Toolbar.TFrame')
        status_left.pack(side="left")
        
        status_label = ttk.Label(status_left, text="就绪", style='Muted.TLabel')
        status_label.pack(side="left", padx=(VideoEditingDesignSystem.SPACING['md'], 0))
        
        # 右侧项目信息
        status_right = ttk.Frame(status_bar, style='Toolbar.TFrame')
        status_right.pack(side="right")
        
        project_info = ttk.Label(status_right, text="项目: 未命名 | 分辨率: 1920x1080 | 帧率: 30fps", style='Muted.TLabel')
        project_info.pack(side="right", padx=(0, VideoEditingDesignSystem.SPACING['md']))
    
    # 事件处理方法
    def new_project(self):
        messagebox.showinfo("新建项目", "创建新的视频项目")
    
    def open_project(self):
        messagebox.showinfo("打开项目", "打开现有项目")
    
    def save_project(self):
        messagebox.showinfo("保存项目", "保存当前项目")
    
    def export_video(self):
        messagebox.showinfo("导出视频", "导出最终视频")
    
    def cut_clip(self):
        messagebox.showinfo("剪切", "剪切选中片段")
    
    def copy_clip(self):
        messagebox.showinfo("复制", "复制选中片段")
    
    def paste_clip(self):
        messagebox.showinfo("粘贴", "粘贴片段")
    
    def undo(self):
        messagebox.showinfo("撤销", "撤销上一步操作")
    
    def redo(self):
        messagebox.showinfo("重做", "重做操作")
    
    def zoom_fit(self):
        messagebox.showinfo("缩放", "缩放到适合窗口")
    
    def show_settings(self):
        messagebox.showinfo("设置", "打开设置面板")
    
    def import_media(self):
        messagebox.showinfo("导入素材", "导入媒体文件")
    
    def refresh_media(self):
        messagebox.showinfo("刷新", "刷新素材库")
    
    def goto_start(self):
        messagebox.showinfo("播放控制", "跳转到开始")
    
    def step_backward(self):
        messagebox.showinfo("播放控制", "后退一帧")
    
    def play_pause(self):
        messagebox.showinfo("播放控制", "播放/暂停")
    
    def step_forward(self):
        messagebox.showinfo("播放控制", "前进一帧")
    
    def goto_end(self):
        messagebox.showinfo("播放控制", "跳转到结尾")
    
    def add_video_track(self):
        messagebox.showinfo("轨道", "添加视频轨道")
    
    def add_audio_track(self):
        messagebox.showinfo("轨道", "添加音频轨道")
    
    def zoom_timeline(self):
        messagebox.showinfo("时间轴", "缩放时间轴")
    
    def toggle_ruler(self):
        messagebox.showinfo("时间轴", "切换标尺显示")
    
    def run(self):
        """运行应用"""
        print("🎬 启动视频混剪系统...")
        print("🎨 采用专业视频编辑软件设计风格")
        print("🎯 参考剪映、Premiere Pro等软件布局")
        print("✨ 深色主题，专业配色方案")
        print("🚀 四区域布局：素材库 + 预览窗口 + 属性面板 + 时间轴")
        print("🖼️ 界面即将打开...")
        
        self.root.mainloop()
        
        print("👋 视频混剪系统已关闭")


if __name__ == "__main__":
    app = VideoEditingMainApp()
    app.run()
